﻿using System.Reflection;
using Sunny.Core.DefinedData;
using Sunny.Core.Domain.Repository;
using Sunny.Core.Exception.Domain;

namespace Sunny.Core.Domain.Model
{
    /// <summary>
    /// The base of the model
    /// </summary>
    public abstract class BaseModel : IModel
    {
        public void CheckStructure()
        {
            var fields = this.GetType().GetProperties();
            foreach (var propertyInfo in fields)
            {
                if(propertyInfo.PropertyType.BaseType == typeof(BaseModel))
                {
                    try
                    {
                        var propertyValue = propertyInfo.GetValue(this, null);
                        if (propertyValue != null)
                        {
                            (propertyValue as BaseModel).CheckStructure();
                        }
                    }
                    catch (TargetInvocationException ex)
                    {
                        if (ex.InnerException is StopUsingModelException)
                        {
                            // Do nonthing, beacuse some properties can't be get
                        }
                    }
                }
            }

            CheckModel();
        }

        protected abstract void CheckModel();
    }
}
